package com.kernel.streamDemo;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.charset.StandardCharsets;

/****************************************
 * @name PipedDemo
 * @description 管道流学习
 * @author 黄彬恒
 * @since 2018/8/17
 ***************************************/
class Sender implements Runnable {

    private PipedOutputStream pos;
    private String msg;

    /**
     * @param msg 需要发送的消息
     */
    Sender(String msg) {
        this.pos = new PipedOutputStream();
        this.msg = msg;
    }

    PipedOutputStream getPos() {
        return pos;
    }

    @Override
    public void run() {
        try {
            this.pos.write(this.msg.getBytes(StandardCharsets.UTF_8));
            this.pos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class Receiver implements Runnable {

    private PipedInputStream pis;

    Receiver() {
        this.pis = new PipedInputStream();
    }

    PipedInputStream getPis() {
        return pis;
    }

    @Override
    public void run() {
        byte[] b = new byte[1024];//定义可以接收的总消息内容长度
        try {
            int temp;
            int length = 0;
            while ((temp = this.getPis().read()) != -1) {
                b[length] = (byte) temp;// 将ASC码转换成byte数组中的元素(byte型变量)
                length++;
            }
            // int length = this.getPis().read(b);
            System.out.println("接收的内容：" + new String(b, 0, length));
            this.pis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class PipedStreamDemo {
    public static void main(String[] args) {
        Sender sender = new Sender("kernel");
        Receiver receiver = new Receiver();
        try {
            sender.getPos().connect(receiver.getPis()); // 使用管道流需要连接好两个线程对象(一定要有这一步)
            new Thread(sender).start();
            new Thread(receiver).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
